package com.auxide.cah;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import com.auxide.util.Logger;

public class Player {

	String name;
	String ip;
	boolean host;
	boolean current;
	ArrayList<String> answers;
	ArrayList<String> questions;

	public Player(){}

	public Player(String name, String ip, boolean host, boolean current){
		this.name = name;
		this.ip = ip;
		this.host = host;
		this.current = current;
		this.answers = new ArrayList<String>();
		this.questions = new ArrayList<String>();
	}

	public String getUserName(){ return name;}
	public String getIP(){ return ip; }
	public boolean isHost(){ return host; }
	public boolean isCurrent() { return current; }
	public ArrayList<String> getAnswers(){ return answers; }
	public ArrayList<String> getQuestions(){ return questions; }

	public void setUserName(String name){ this.name = name; }
	public void setIP(String ip){ this.ip = ip; }
	public void setHost(boolean host){ this.host = host; }
	public void setCurrent(boolean current){ this.current = current; }
	
	@Override 
	public String toString() {
		return this.name + ":" + this.ip;
	}

	public String toJSON(){
		JSONObject jo = new JSONObject();
		try{
			JSONArray a = new JSONArray();
			for(String s : answers){
				a.put(s);
			}
			
			JSONArray q = new JSONArray();
			for(String s : questions){
				q.put(s);
			}
			
			jo.put("Name", name);
			jo.put("IP", ip);
			jo.put("Host", host);
			jo.put("Current", current);
			jo.put("Answers", a);
			jo.put("Questions", q);
		}catch(Exception e){
			Logger.e(e);
		}

		return jo.toString();
	}
	
	public static Player fromJSON(String json){
		Player p = null;
		try{
			JSONObject jo = new JSONObject(json);
			JSONArray a = jo.getJSONArray("Answers");
			JSONArray q = jo.getJSONArray("Questions");
			
			ArrayList<String> answers = new ArrayList<String>();
			ArrayList<String> questions = new ArrayList<String>();
			
			for(int i = 0; i < a.length(); i++){
				answers.add(a.getString(i));
			}
			
			for(int i = 0; i < q.length(); i++){
				questions.add(q.getString(i));
			}
			
			p = new Player(jo.getString("Name"), jo.getString("IP"), jo.getBoolean("Host"), jo.getBoolean("Current"));
			p.answers = answers;
			p.questions = questions;
			
		}catch(Exception e){
			Logger.e(e);
		}
		return p;
	}
}
